<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 商品销量明细
 *
 * @icon fa fa-circle-o
 */
class Reportgoods extends Backend {

    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\Goods;
    }

    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $admin_info = db('admin')->where('id', $this->auth->id)->find();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter = $this->request->get("filter", '');
            $filter = json_decode($filter, true);
            $createtime = '';
            $otherwhere = [];
            if (isset($filter['createtime'])) {

                $op = $this->request->get("op", '');
                $op = json_decode($op, true);
                $createtime = $filter['createtime'];
                $sym = $op['createtime'];
                $v = str_replace(' - ', ',', $createtime);
                $arr = array_slice(explode(',', $v), 0, 2);
                if (stripos($v, ',') === false || !array_filter($arr))

                //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } else if ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                $otherwhere['o.createtime'] = [str_replace('RANGE', 'BETWEEN', $sym), $arr];
            }

            if (isset($filter['cate_id'])) {
                $otherwhere['g.cate_id'] = $filter['cate_id'];
            }
            if (isset($filter['brand_id'])) {
                $otherwhere['g.brand_id'] = $filter['brand_id'];
            }

            if (isset($filter['goods_title'])) {
                $otherwhere['g.goods_title'] = ['like', '%' . $filter['goods_title'] . '%'];
            }

            if (isset($filter['province'])) {
                $otherwhere['ub.province'] = $filter['province'];
            }

            if (isset($filter['city'])) {
                $otherwhere['ub.city'] = $filter['city'];
            }

            if (isset($filter['area'])) {
                $otherwhere['ub.area'] = $filter['area'];
            }

            if (isset($filter['quarters_id'])) {
                $otherwhere['ub.quarters_id'] = $filter['quarters_id'];
            }

            if (isset($filter['unit_id'])) {
                $otherwhere['ub.unit_id'] = $filter['unit_id'];
            }

            if (isset($filter['room_id'])) {
                $otherwhere['ub.room_id'] = $filter['room_id'];
            }




//            var_dump($createtime);die;
            $filterAlias['cate_id'] = 'g.cate_id';
            $filterAlias['brand_id'] = 'g.brand_id';

            $noselectField[] = 'createtime';
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null, null, [], $filterAlias, [], $noselectField);
            $admin_where = [];

            if ($admin_info['identity'] == 1) {
                if ($admin_info['province'] != 0) {
                    $admin_where['ub.province'] = $admin_info['province'];
                }
                if ($admin_info['city'] != 0) {
                    $admin_where['ub.city'] = $admin_info['city'];
                }
                if ($admin_info['area'] != 0) {
                    $admin_where['ub.area'] = $admin_info['area'];
                }
                if ($admin_info['quarters_id'] != 0) {
                    $admin_where['ub.quarters_id'] = $admin_info['quarters_id'];
                }
                if ($admin_info['unit_id'] != 0) {
                    $admin_where['ub.unit_id'] = $admin_info['unit_id'];
                }
                if ($admin_info['room_id'] != 0) {
                    $admin_where['ub.room_id'] = $admin_info['room_id'];
                }
            } else if ($admin_info['identity'] == 2) {
                $admin_where['ub.box_no'] = ['in', $admin_info['box_nos']];
            }
            $total = db('goods')
                    ->alias('g')
                    ->join('fa_user_box_goods ubg', 'ubg.goods_id=g.goods_id')
                    ->join('fa_user_box ub', 'ub.user_box_id=ubg.user_box_id')
                    ->join('fa_goods_brand gb', 'gb.brand_id = g.brand_id', 'left')
                    ->join('fa_goods_cate gc', 'gc.cate_id = g.cate_id', 'left')
                    ->where($where)
                    ->where($admin_where)
                    ->group('g.goods_id')
                    ->select();

            $total = count($total);

            $list = db('goods')
                    ->alias('g')
                    ->field('g.goods_id,g.goods_title,gb.brand_title,gc.cate_title')
                    ->join('fa_user_box_goods ubg', 'ubg.goods_id=g.goods_id')
                    ->join('fa_user_box ub', 'ub.user_box_id=ubg.user_box_id')
                    ->join('fa_goods_brand gb', 'gb.brand_id = g.brand_id', 'left')
                    ->join('fa_goods_cate gc', 'gc.cate_id = g.cate_id', 'left')
                    ->where($where)
                    ->where($admin_where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->group('g.goods_id')
                    ->select();

            $list = collection($list)->toArray();

            if ($list) {
                foreach ($list as &$val) {
                    $val['purchases_num'] = db('stock_log')
                            ->alias('o')
                            ->join('fa_user_box_goods ubg', 'ubg.box_goods_id=o.box_goods_id')
                            ->join('fa_user_box ub', 'ub.user_box_id=ubg.user_box_id')
                            ->join('fa_goods g', 'ubg.goods_id=g.goods_id')
                            ->where('o.goods_id', $val['goods_id'])
                            ->where('o.change_type', 0)
                            ->where('o.change_matters', '<', 3)
                            ->where($otherwhere)
                            ->sum('change_amount');


                    $val['sale_num'] = db('order')
                            ->alias('o')
                            ->join('order_goods og', 'og.order_id = o.order_id')
                            ->join('fa_user_box_goods ubg', 'ubg.box_goods_id=og.box_goods_id')
                            ->join('fa_user_box ub', 'ub.user_box_id=ubg.user_box_id')
                            ->join('fa_goods g', 'ubg.goods_id=g.goods_id')
                            ->where('og.goods_id', $val['goods_id'])
                            ->where('o.status', 10)
                            ->where('o.type', 1)
                            ->where($otherwhere)
                            ->sum('buy_num');
                    $sale_num = $val['sale_num'];
                    if ($sale_num == 0) {
                        $sale_num = 1;
                    }

                    $purchases_num = $val['purchases_num'];
                    if ($purchases_num == 0) {
                        $purchases_num = 1;
                    }
                    $val['sale_percent'] = ($sale_num / $purchases_num) * 100;
                    $val['sale_percent'] = sprintf("%.2f", $val['sale_percent']) . '%';

                    $purchase_price = db('goods')->where('goods_id', $val['goods_id'])->value('purchase_price');

                    $total_sale_price = db('order')
                            ->alias('o')
                            ->field('sum(ubg.selling_price*og.buy_num) as total_sale_price')
                            ->join('order_goods og', 'og.order_id = o.order_id')
                            ->join('fa_user_box_goods ubg', 'ubg.box_goods_id=og.box_goods_id')
                            ->join('fa_user_box ub', 'ub.user_box_id=ubg.user_box_id')
                            ->join('fa_goods g', 'ubg.goods_id=g.goods_id')
                            ->where('og.goods_id', $val['goods_id'])
                            ->where('o.status', 10)
                            ->where('o.type', 1)
                            ->where($otherwhere)
                            ->find();


                    $profit = $total_sale_price['total_sale_price'] - $purchase_price * $val['sale_num'];
                    $val['profit'] = sprintf("%.2f", $profit);
                    if ($profit == 0) {
                        $profit = 1;
                    }

                    if ($total_sale_price['total_sale_price'] == 0) {
                        $total_sale_price['total_sale_price'] = 1;
                    }
                    $profit_rate = ($profit / $total_sale_price['total_sale_price']) * 100;
                    $val['profit_rate'] = sprintf("%.2f", $profit_rate) . '%';
                }
                unset($val);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $brandList = db('goods_brand')->field('brand_id as id,brand_title as name')->order('sort')->select();
        $cateList = db('goods_cate')->field('cate_id as id,cate_title as name')->order('sort')->select();
        $this->view->assign('identity',$admin_info['identity']);
        $this->view->assign("brandlist", $brandList);
        $this->view->assign("catelist", $cateList);
        return $this->view->fetch();
    }

    public function detail() {
        $id = $this->request->param('ids');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter", '');

            $filter = (array) json_decode($filter, TRUE);

            $type = 1;

            if (isset($filter['type'])) {
                $type = $filter['type'];
            }

            $is_search = 0;
            $time = [];
            if (isset($filter['createtime'])) {
                $v = str_replace(' - ', ',', $filter['createtime']);
                $time = array_slice(explode(',', $v), 0, 2);
                $is_search = 1;
            } else {
                if ($type == 1) {
                    $time[0] = date('Y-m-d 00:00:00', strtotime('-6 days', time()));
                }

                if ($type == 2) {
                    $time[0] = date('Y-m-01 00:00:00');
                }

                if ($type == 3) {
                    $time[0] = date('Y-01-01 00:00:00');
                }

                if ($type == 4) {
                    $time[0] = '2018-01-01 00:00:00';
                }
                $time[1] = date('Y-m-d 23:59:59', time());
            }

            $day_list = [];

            //日报表
            if ($type == 1) {
                $diff = timeDiff(strtotime($time[0]), strtotime($time[1]));
                $diff_day = $diff['day'];

                for ($i = 0; $i <= $diff_day; $i++) {
                    $day_time = strtotime('+' . $i . ' days', strtotime($time[0]));
                    $day_list[] = ['day' => date('Y-m-d', $day_time), 'start' => date('Y-m-d 00:00:00', $day_time), 'end' => date('Y-m-d 23:59:59', $day_time)];
                }
                $total = $diff_day;
            }

            //周报表
            if ($type == 2) {

                $diff = diffDate(date('Y-m-d', strtotime($time[0])), date('Y-m-d', strtotime($time[1])));

                $diff_month = $diff['month'];

                for ($m = $diff_month; $m >= 0; $m--) {
                    $firstday = strtotime("-" . $m . " months" . date('Y-m-01', strtotime($time[1])));

                    $week_num = 5;
                    if ($is_search) {

                        $date_now = date('j'); //得到今天是几号
                        $cal_result = ceil($date_now / 7); //计算是第几个星期几
                        $week_num = $cal_result + 1;
                        $firstday = strtotime("-" . $m . " months" . date('Y-m-d', strtotime($time[1])));
                    }


                    //计算本月头一天的星期一
                    $monday = $firstday - 86400 * (date('N', $firstday) - 1); //计算第一个周一的日期
                    //由于每个月只有四周 让 $i 从 1 到 5 增加即可
                    for ($i = 0; $i <= $week_num; $i++) {
                        $start = date("Y-m-d", $monday + ($i - 1) * 86400 * 7); //起始周一
                        $end = date("Y-m-d", $monday + $i * 86399 * 7); //结束周日
                        if (date('Y-m', strtotime($end)) != date('Y-m', $firstday)) {
                            continue;
                        }

                        if (date('Y-m-d', strtotime($start)) > date('Y-m-d', strtotime($time[1]))) {
                            continue;
                        }


                        $day_list[] = ['day' => $start . '-' . $end, 'start' => $start . ' 00:00:00', 'end' => $end . ' 23:59:59'];
                    }
                }
                $total = count($day_list);
            }

            array_reverse($day_list);

            //月报表
            if ($type == 3) {
                $diff = diffDate(date('Y-m-d', strtotime($time[0])), date('Y-m-d', strtotime($time[1])));

                $diff_month = $diff['month'];

                for ($i = $diff_month; $i >= 0; $i--) {
                    $month = strtotime("-" . $i . " months" . date('Y-m-d', strtotime($time[1])));

                    $day_list[] = ['day' => date('Y-m', $month), 'start' => date('Y-m-01 00:00:00', $month), 'end' => date('Y-m-01 00:00:00', strtotime("+1 months" . date('Y-m-d', $month)))];
                }

                $total = count($diff_month + 1);
            }

            //年报表
            if ($type == 4) {
                $diff = diffDate('2018-01-01', date('Y-m-d', strtotime($time[0])));

                $diff_year = $diff['year'];

                for ($i = $diff_year; $i >= 0; $i--) {
                    $year = strtotime("-" . $i . " year" . date('Y-m-d', strtotime($time[0])));

                    $day_list[] = ['day' => date('Y', $year), 'start' => date('Y-01-01 00:00:00', $year), 'end' => date('Y-12-31 23:59:59', $year)];
                }

                $total = count($diff_year + 1);
            }

            $list = [];
            foreach ($day_list as $val) {
                $data['day'] = $val['day'];
                $data['purchases_num'] = db('stock_log')
                        ->alias('o')
                        ->where('o.goods_id', $id)
                        ->where('o.change_type', 0)
                        ->where('o.change_matters', '<', 3)
                        ->whereTime('o.createtime', 'between', [$val['start'], $val['end']])
                        ->sum('change_amount');
                $data['sale_num'] = db('order')
                        ->alias('o')
                        ->join('order_goods og', 'og.order_id = o.order_id')
                        ->join('fa_user_box_goods ubg', 'ubg.box_goods_id=og.box_goods_id')
                        ->join('fa_user_box ub', 'ub.user_box_id=ubg.user_box_id')
                        ->join('fa_goods g', 'ubg.goods_id=g.goods_id')
                        ->where('og.goods_id', $id)
                        ->where('o.status', 10)
                        ->where('o.type', 1)
                        ->whereTime('o.createtime', 'between', [$val['start'], $val['end']])
                        ->sum('buy_num');

                $sale_num = $data['sale_num'];
                if ($sale_num == 0) {
                    $sale_num = 1;
                }

                $purchases_num = $data['purchases_num'];
                if ($purchases_num == 0) {
                    $purchases_num = 1;
                }
                $data['sale_percent'] = ($sale_num / $purchases_num) * 100;
                $data['sale_percent'] = sprintf("%.2f", $data['sale_percent']) . '%';

                $data['start'] = $val['start'];
                $data['end'] = $val['end'];
                $list[] = $data;
            }


            $result = array("total" => $total, "rows" => array_reverse($list));

            return json($result);
        }
        $goods_title = db('goods')->where('goods_id', $id)->value('goods_title');
        $this->assign('goods_title', $goods_title);
        $this->assign('id', $id);
        return $this->view->fetch();
    }

}
